/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.service.impl;

import com.bifrost.constant.OrderStatusHistoryOrderType;
import com.bifrost.entity.Order;
import com.bifrost.entity.OrderStatusHistory;
import com.bifrost.entity.User;
import com.bifrost.event.OrderStatusChangedEvent;
import com.bifrost.repository.OrderStatusHistoryRepository;
import com.bifrost.service.AdminUserService;
import com.bifrost.service.OrderService;
import com.bifrost.service.OrderStatusHistoryService;
import com.bifrost.service.SmsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 订单状态日志记录服务
 *
 * @author joewee
 * @version 1.0.0
 * @Date 2018/1/5 11:29
 */
@Service
public class OrderStatusHistoryServiceImpl implements OrderStatusHistoryService, ApplicationContextAware {
    @Autowired
    OrderService orderService;
    @Autowired
    SmsService smsService;
    @Autowired
    AdminUserService userService;
    @Autowired
    OrderStatusHistoryRepository orderStatusHistoryRepository;
    protected ApplicationContext applicationContext;

    /**
     * 添加订单状态日志记录
     *
     * @param order
     * @param comments
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public OrderStatusHistory writeHistory(Order order, String comments) {

        return writeHistory(order, comments, Boolean.FALSE,null);
    }

    /**
     * 添加订单状态记录
     *
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public OrderStatusHistory writeHistory(Order order) {
        return writeHistory(order, null);
    }

    /**
     * 添加订单状态记录
     *
     * @param order    订单
     * @param comments 状态描述
     * @param notified 是否已通知客户
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public OrderStatusHistory writeHistory(Order order, String comments, Boolean notified , String code) {
        //记录订单状态
        OrderStatusHistory history = new OrderStatusHistory();
        history.setOrder(order);
        history.setDateAdded(new Date());
        history.setStatus(order.getOrderStatus());
        history.setCustomerNotified(notified);
        history.setOrderType(OrderStatusHistoryOrderType.ORDER);
        String orderType = "订单";
        if (!StringUtils.isEmpty(comments)) {
            history.setStatusComments(String.format("%s:%s%s", orderType, order.getOrderNumber(), comments));
        } else {
            history.setStatusComments(String.format("%s:%s%s", orderType, order.getOrderNumber(), orderService.getStatusDesc(order)));
        }
        if(StringUtils.isNotBlank(code)){
            User user = userService.findUserByCode(code.trim());
            history.setUserId(user.getId());
        }

        history = orderStatusHistoryRepository.save(history);
        if (!Boolean.TRUE.equals(notified)) {
            OrderStatusChangedEvent event = new OrderStatusChangedEvent(order.getOrderId(), history);
            applicationContext.publishEvent(event);
        }
        return history;
    }

    /**
     * 保存记录
     *
     * @param history
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public OrderStatusHistory save(OrderStatusHistory history) {
        return orderStatusHistoryRepository.save(history);
    }

    /**
     * 查询所有未通知到客户的历史记录
     *
     * @return
     */
    @Override
    public List<OrderStatusHistory> findAllUnnotifiedHistories() {
        return orderStatusHistoryRepository.findAllUnnotifiedHistories();
    }

    /**
     * 执行通知
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void notified() {
        List<OrderStatusHistory> histories = findAllUnnotifiedHistories();
        if (histories != null && !histories.isEmpty()) {
            histories.forEach(history -> {
                Order order = history.getOrder();
                String phone = order.getCustomer().getCustomerPhone();
                String msg = history.getStatusComments();
                if (!Boolean.TRUE.equals(history.getCustomerNotified()) && StringUtils.isNotEmpty(smsService.sendCustomerMessage(phone, String.format("%s", msg)))) {
                    history.setCustomerNotified(Boolean.TRUE);
                    save(history);
                }
            });
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     * 查询指定订单某状态的操作时间
     *
     * @param orderId
     * @param status
     * @return
     */
    @Override
    public Date getTime(Long orderId, String status) {
        return orderStatusHistoryRepository.getTimeOfOrder(orderId,status);
    }

}
